package com.amoby.main.action.business;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.amoby.base.common.BaseAction;
import com.amoby.base.common.Pager;
import com.amoby.main.entity.Business;
import com.amoby.main.entity.Channel;
import com.amoby.main.entity.SysUsers;
import com.amoby.main.service.AlipayService;
import com.amoby.main.service.AreaService;
import com.amoby.main.service.BusinessService;
import com.amoby.main.service.BusinessTypeService;
import com.amoby.main.service.ChannelService;
import com.google.common.collect.Maps;

/**
 * ParamAction Desc：商户管理
 * @address http://www.yingmob.com/
 * @author zhaoyy
 * @date 2016年4月11日 上午10:44:37
 */
@Controller
public class BusinessAction extends BaseAction {
    @Autowired
    private BusinessService     businessService;
    @Autowired
    private BusinessTypeService businessTypeService;
    @Autowired
    private AreaService         areaService;
    @Autowired
    private AlipayService       alipayService;
    @Autowired
    private ChannelService      channelService;


    /**
     * 初始化时间
     * @author Lasing 2016-6-3 上午10:55:32
     * @param binder
     * @throws Exception
     */
    @InitBinder
    protected void init(WebDataBinder binder) throws Exception {
        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
    /**
     * 初始化页面
     * @author Lasing 2016-6-3 上午10:55:40
     * @return
     */
    @RequestMapping(value = "/menus/business_mgr.html", method = RequestMethod.GET)
    public String listPage(ModelMap model) {
     // 商户类型父类型
        model.put("shopType", businessTypeService.queryParent());
        model.put("areas", areaService.queryParent());
        return AD_HTML + "business/business_mgr";
    }


    /**
     * 商户分页查询
     * @author Lasing 2016-6-3 上午10:56:44
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/business/list.html", method = RequestMethod.POST)
    public Object list(HttpServletRequest request) {
        SysUsers user = getUser();
        Channel channel = channelService.getChannelByUserId(user.getUserId()); //根据userId获取渠道信息
        Pager pager = createPager(request);
        pager.addParam("startDate", getRequestParams(String.class, request, "startDate"));
        pager.addParam("endDate", getRequestParams(String.class, request, "endDate"));
        pager.addParam("username", getRequestParams(String.class, request, "username"));
        pager.addParam("shopName", getRequestParams(String.class, request, "shopName"));
        pager.addParam("id", getRequestParams(String.class, request, "id"));
        if(channel!=null){
            pager.addParam("channelId", channel.getId());   //渠道id
        }
        pager.addParam("status", getRequestParams(String.class, request, "status"));
        pager.addParam("shopStatus", getRequestParams(Integer.class, request, "shopStatus"));
        pager.addParam("discount", getRequestParams(Integer.class, request, "discount"));
        pager.addParam("shopType", getRequestParams(Integer.class, request, "shopType"));
        pager.addParam("shopArea", getRequestParams(Integer.class, request, "shopArea"));
        pager.addParam("isBrokerage", getRequestParams(Integer.class, request, "isBrokerage"));
        pager = businessService.query(pager);
        return getGridData(pager);
    }

    
    
    /**
     * 商户新增
     * @author Lasing 2016-6-3 上午10:57:02
     * @param business
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/business/add.html", method = RequestMethod.POST)
    public Object add(Business business, HttpServletRequest request) {
        SysUsers user = getUser();
        Channel channel = channelService.getChannelByUserId(user.getUserId()); //根据userId获取渠道信息
        Map<String, Object> result = getResultMap();
        try {
            Double brokerage = business.getBrokerage() == null ? 0d : new BigDecimal(business.getBrokerage()).divide(new BigDecimal(100))
                    .doubleValue();
            business.setBrokerage(brokerage);
            if (business != null && businessService.add(business,channel) > 0) {
                result.put(RESULT, true);
                result.put(MESSAGE, "添加商家成功！");
            } else {
                result.put(MESSAGE, "添加商家失败！");
            }
        } catch (Exception e) {
            result.put(MESSAGE, "添加商家异常！");
            getLog(this).error("添加商家异常！", e);
        }
        return result;
    }

    /**
     * 商户修改
     * @author Lasing 2016-6-3 上午10:57:12
     * @param business
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/business/upd.html", method = RequestMethod.POST)
    public Object upd(Business business, HttpServletRequest request) {
        Map<String, Object> result = getResultMap();
        try {
            
            Double brokerage = business.getBrokerage() == null ? 0d : new BigDecimal(business.getBrokerage().toString()).divide(new BigDecimal(100))
                    .doubleValue();
            business.setBrokerage(brokerage);
            if ("".equals(business.getShopSubclass())) {
                business.setShopSubclass(null);
            }
            if (business != null && business.getId() != null && businessService.upd(business) > 0) {
                //修改了商户名就去更新二维码(这里如果系统更新了商户就不知道所以不更新)
                //alipayService.createAlipayCode(business.getId().toString(), business.getShopName());
                result.put(RESULT, true);
                result.put(MESSAGE, "修改商家成功！");
            } else {
                result.put(MESSAGE, "修改商家失败！");
            }
        } catch (Exception e) {
            result.put(MESSAGE, "修改商家异常！");
            getLog(this).error("修改商家异常！", e);
        }
        return result;
    }

    /**
     * 商户重置密码
     * @author Lasing 2016-6-3 上午10:57:29
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/business/resetPassword.html", method = RequestMethod.POST)
    public Object reset_pwd(HttpServletRequest request) {
        Map<String, Object> result = getResultMap();
        try {
            Long id = getRequestParams(Long.class, request, "id");
            Integer userId = getRequestParams(Integer.class, request, "userId");
            if (id != null && businessService.reset_pwd(id, userId) > 0) {
                result.put(RESULT, true);
                result.put(MESSAGE, "重置商家密码成功！");
            } else {
                result.put(MESSAGE, "重置商家密码失败！");
            }
        } catch (Exception e) {
            result.put(MESSAGE, "重置商家密码异常！");
            getLog(this).error("重置商家密码异常！", e);
        }
        return result;
    }

    /**
     * 删除商户
     * @author Lasing 2016-6-3 上午10:58:01
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/business/del.html", method = RequestMethod.POST)
    public Object del(HttpServletRequest request) {
        Map<String, Object> result = getResultMap();
        try {
            Long id = getRequestParams(Long.class, request, "id");
            Integer userId = getRequestParams(Integer.class, request, "userId");
            if (id != null && businessService.del(id, userId) > 0 ) {
                result.put(RESULT, true);
                result.put(MESSAGE, "删除商家成功！");
            } else {
                result.put(MESSAGE, "删除商家失败！");
            }
        } catch (Exception e) {
            result.put(MESSAGE, "删除商家异常！");
            getLog(this).error("删除商家异常！", e);
        }
        return result;
    }

    /**
     * 商家管理 放开用户名修改权限 验证唯一性 廖江红 添加 2015-3-25 为了不影响其他验证，单独写了一个
     * @param username id
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/business/checkUnById.html", method = RequestMethod.POST)
    public Object checkUnById(String username, Long id, HttpServletRequest request) {
        logger.info("商家管理 放开用户名修改权限 验证唯一性==>shopId:" + id);
        logger.info("商家管理 放开用户名修改权限 验证唯一性==>username:" + username);
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            if (StringUtils.isBlank(username)) {
                result.put(RESULT, false);
                result.put(MESSAGE, "用户名不能为空！");
            }
            int count = businessService.checkUserNameById(username, id);
            result.put(RESULT, true);
            result.put("count", count);
        } catch (Exception e) {
            result.put(RESULT, false);
            result.put(MESSAGE, "验证用户名异常！");
        }
        return result;
    }
    
    /**
     * 验证渠道名称唯一
     * @author Lasing 2016-6-22 上午11:25:26
     * @param username
     * @param id
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/business/checkShopName.html", method = RequestMethod.POST)
    public Object checkShopName(String shopName, Long id, HttpServletRequest request) {
        logger.info("商家管理 放开用户名修改权限 验证唯一性==>shopId:" + id);
        logger.info("商家管理 放开用户名修改权限 验证唯一性==>shopName:" + shopName);
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            if (StringUtils.isBlank(shopName)) {
                result.put(RESULT, false);
                result.put(MESSAGE, "渠道名称不能为空！");
            }
            int count = businessService.checkShopName(shopName, id);
            result.put(RESULT, true);
            result.put("count", count);
        } catch (Exception e) {
            result.put(RESULT, false);
            result.put(MESSAGE, "验证渠道名称异常！");
        }
        return result;
    }
    
    /**
     * 生成二维码
     */
    @ResponseBody
    @RequestMapping(value = "/business/crqrcode.do")
    public Object qrcode(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> params = Maps.newHashMap();
        Map<String,Object> resultMap = new HashMap<String,Object>();
        String merchantId = getRequestParams(String.class, request, "id");
        String merchantName = getRequestParams(String.class, request, "shopName");
        params = alipayService.createAlipayCode(merchantId, merchantName);
        logger.debug("成功二维码返回结果数据==============="+params);
        if(params!=null &&"success".equals(params.get("result"))){
            Business business = businessService.findById(Long.parseLong(merchantId));
            resultMap.put(RESULT, "true");
            resultMap.put(MESSAGE, params.get("message"));
            resultMap.put("qrcodeurl", business.getQrcodeurl());
        }else{
          resultMap.put(RESULT, "fail");
          resultMap.put(MESSAGE, params.get("message"));
        }
        return resultMap;
    }
    // =========================================支付宝商户开始=============================================
   /* *//**
     * 初始化页面
     * @return
     *//*
    @RequestMapping(value = "/menus/business_alipay_list.html", method = RequestMethod.GET)
    public String alipayListPage() {
        return AD_HTML + "business/alipay_list";
    }

    *//**
     * 支付宝商户列表
     * @param request
     * @return
     *//*
    @ResponseBody
    @RequestMapping(value = "/business/alipay_list.html", method = RequestMethod.POST)
    public Object alipayList(HttpServletRequest request) {
        Pager pager = createPager(request);
        pager.addParam("username", getRequestParams(String.class, request, "username"));// 用户名
        pager.addParam("shopName", getRequestParams(String.class, request, "shopName"));// 商户名称
        pager.addParam("shopType", getRequestParams(Integer.class, request, "shopType"));// 商户类型
        pager.addParam("shopSubclass", getRequestParams(Integer.class, request, "shopSubclass"));// 商户子类
        pager.addParam("shopStatus", getRequestParams(Integer.class, request, "shopStatus"));// 显示状态
        pager.addParam("status", getRequestParams(Integer.class, request, "status"));// 登陆状态
        pager = businessMgr.alipayQuery(pager);
        return getGridData(pager);
    }
    
    */
    
    /*
    @ResponseBody
    @RequestMapping(value = "/selectFiles.html")
    public Object selectFiles(Integer fId, HttpServletRequest request, ModelMap model) {
        Map<String, Object> result = getResultMap();
        SysFiles files = fileMgrSv.getEffectivFile(fId);
        result.put("files", files);
        result.put(RESULT, true);
        result.put(MESSAGE, "查询成功！");
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/selectPhoto.html")
    public Object selectPhoto(Integer gId, HttpServletRequest request, ModelMap model) {
        Map<String, Object> result = getResultMap();
        List<SysFiles> groupFile = fileMgrSv.getGroupFile(gId);
        result.put("groupFile", groupFile);
        result.put(RESULT, true);
        result.put(MESSAGE, "查询成功！");
        return result;
    }

    *//**
     * 页面点击生成（查看）二维码
     * @param request
     * @param model
     * @return
     * @throws Exception
     *//*
    @ResponseBody
    @RequestMapping(value = "/deatailCode.html")
    public void deatailCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String merchantId = getRequestParams(String.class, request, "merchantId");
        // 二维码地址对应H5支付页面
//        String content = getContent(merchantId);
        Business bus = businessMgr.findById(Long.parseLong(merchantId));
        String content = bus.getQrcodeurl();
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        Map<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 500, 500, hints);
            bitMatrix = updateBit(bitMatrix, 20);  // 生成新的bitMatrix
        } catch (WriterException e1) {
            logger.error("qrCode异常：{二维码生成出错}", e1);
        }
        ServletOutputStream sos = null;
        try {
            response.setHeader("Cache-Control", "no-store");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/png");
            BufferedImage buffImg = ZxUtil.toBufferedImage(bitMatrix);
            sos = response.getOutputStream();
            ImageIO.write(buffImg, "jpg", sos);
            sos.flush();
        } catch (Exception e) {
            logger.error("qrCode异常：{二维码生成出错}", e);
        } finally {
            if (sos != null) try {
                sos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    *//**
     * 二维码地址
     * @param request
     * @param model
     * @return
     * @throws Exception
     *//*
    @ResponseBody
    @RequestMapping(value = "/qrcodeurl.html")
    public Object qrcodeurl(HttpServletRequest request, ModelMap model) throws Exception {
        Map<String, Object> result = getResultMap();
        String merchantId = getRequestParams(String.class, request, "merchantId");
        
        Business bus = businessMgr.findById(Long.parseLong(merchantId));
        String content = bus.getQrcodeurl();
        result.put("qrcodeurl", content);
        result.put(RESULT, true);
        result.put(MESSAGE, "查询成功！");
        return result;
    }*/
    
    // =========================================支付宝商户结束=============================================
}
